# -*- coding: utf-8 -*-
import json
from flask import Flask, request
import requests

# import psycopg2

app = Flask(__name__)

'''
class PostgresData:
    def __init__(self):
        self.username = 'postgres'
        self.password = 'postgres'
        self.host = '10.10.3.11'
        self.port = 5432

    def push_alert_data(self, alerts, status):
        conn = psycopg2.connect(database='xdrlog', user=self.username, password=self.password, host=self.host,
                                port=self.port)
        conn.set_client_encoding('utf-8')
        cur = conn.cursor()
        date = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        data = []
        for alert in alerts:
            label = alert['labels']
            # clickhouse
            level = 3
            if label['job'] == 'clickhouse_status':
                ip_port = label['instance']
                master = 'yes'
                if ip_port.find('8223') != -1:
                    master = 'no'
                    level = 2
                content = {'ip': ip_port[0:ip_port.find(':')], 'status': status, 'master': master}
                data.append([level, label['job'].upper(), json.dumps(content), date])
            # host
            elif label['job'] == 'host_status':
                content = {'ip': label['instance'], 'status': status, 'master': ''}
                data.append([level, label['job'].upper(), json.dumps(content), date])
            else:
                ip_port = label['instance']
                content = {'ip': ip_port[0:ip_port.find(':')], 'status': status, 'master': ''}
                data.append([level, label['job'].upper(), json.dumps(content), date])

        # 执行插入语句
        sql = "INSERT INTO public.td_alarm (level, type, content, create_date) VALUES (%s, %s, %s, %s)"
        cur.executemany(sql, data)
        conn.commit()
        cur.close()
        conn.close()
'''


def send_alert_data(content):
    data = {
        "msgtype": "text",
        "text": {
            "content": content,
            "mentioned_mobile_list": ["13146185496"]
        }
    }

    # 发送 POST 请求
    response = requests.post(
        url="https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=9f3f876f-dce5-4bb7-856f-aabb9d4b400b",
        headers={"Content-Type": "application/json"},
        data=json.dumps(data)
    )

    # 如果需要查看响应的内容
    if response.status_code == 200:
        print(response.json())
    else:
        print("Error:", response.text)


@app.route('/webhook', methods=["POST"])
def webhook_server():
    alert_data = json.loads(request.get_data())
    print('发送信息')
    # alerts = alert_data["alerts"]
    send_alert_data(alert_data['message'])
    # print(alerts)
    # pd = PostgresData()
    # if alert_data['message'].find('触发') != -1:
    #     pd.push_alert_data(alerts, 'down')
    # else:
    #     pd.push_alert_data(alerts, 'up')

    return {"status": "ok"}


if __name__ == "__main__":
    app.run(debug=False, host='192.168.137.100', port=18088)
